package arithmetic1.search;

/*
    二分查找:要求数组必须要有序
 */
public class BinarySearch {
    public static void main(String[] args) {
        int arr[]={0,1,2,3,4,5,6,7,8,9};
        int index=binarySearch(arr,8);
        System.out.println(index);
    }

    //二分查找 假设数组已经是升序
    public static int binarySearch(int arr[],int start,int end,int num){
        int mid=(start+end)/2;
        if(start<=end){      //数据合法
            if(num==arr[mid]){
                return mid;
            }else if(num<arr[mid]){     //在前面一半继续查找
                return binarySearch(arr,start,mid-1,num);
            }else{  //在后面一半继续查找
                return binarySearch(arr,mid+1,end,num);
            }
        }
        return -1;
    }

    public static int binarySearch(int arr[],int num){
        return binarySearch(arr,0,arr.length-1,num);
    }
}
